package com.vf.cloud.api.sys.controller;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.vf.cloud.common.datasource.annotation.Tx;
import com.vf.cloud.common.domain.Dept;
import com.vf.cloud.common.domain.Role;
import com.vf.cloud.common.domain.RoleMenu;
import com.vf.cloud.common.domain.User;
import com.vf.cloud.common.domain.UserRole;
import com.vf.cloud.common.util.R;
import com.vf.cloud.common.util.UuidUtil;

@RestController
@RequestMapping("/sys/role")
public class RoleController {

	@GetMapping(value = { "/findList" }, produces = "application/json; charset=utf-8")
	public R<Page<Role>> findList(@RequestParam(name = "keywords", required = false, defaultValue = "") String keywords,
			@RequestParam(name = "status", required = false, defaultValue = "") String status,
			@RequestParam(name = "cur", required = false, defaultValue = "1") int cur,
			@RequestParam(name = "limit", required = false, defaultValue = "10") int limit) throws Exception {

		String sqlExceptSelect = " FROM " + Role.TABLE_NAME + " o  WHERE del_flag='0' ";
		if (!StrKit.isBlank(keywords)) {
			sqlExceptSelect += " AND ( O.NAME LIKE '%" + keywords + "%' OR   O.CODE LIKE '%" + keywords + "%' ) ";
		}
		if (!StrKit.isBlank(status)) {
			sqlExceptSelect += " AND O.STATUS='" + status + "' ";
		}
		sqlExceptSelect += "  ORDER BY   O.ORDER_NUM asc ";
		Page<Role> roles = Role.dao.paginate(cur, limit, "select * ", sqlExceptSelect);
		return R.ok(roles);
	}

	@Tx
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public R<Role> save(Role role) {
		try {
			if (StrKit.isBlank(role.getName())) {
				return R.failed("名称不可以为空！");
			}
			Role rl = Role.findByCode(role.getCode());
			if (rl != null) {
				return R.failed("标识已被使用！");
			}
			if (StrKit.notBlank(role.getId())) {
				if (role.update()) {
					return R.ok(role);
				} else {
					return R.failed("更新失败！");
				}
			} else {
				role.setId(UuidUtil.getUUID());
				role.setCreateTime(LocalDateTime.now());
				if (role.save()) {
					return R.ok(role);
				} else {
					return R.failed("保存失败！");
				}
			}
		} catch (Exception e) {
			return R.failed(e.getMessage());
		}
	}

	@Tx
	@RequestMapping(value = "/delete", method = RequestMethod.GET)
	public R<String> delete(@RequestParam(name = "ids") String ids) throws Exception {
		try {
			if (StrKit.isBlank(ids))
				return R.failed("参数必填！");
			List<String> result = Arrays.asList(ids.split(","));
			if (result == null)
				return R.failed("参数无效！");
			for (String id : result) {
				Role role = Role.dao.findById(id);
				if (role != null && !StrKit.equals(role.getCode(), "SuperSystem")) {
					role.setDelFlag("1");
					role.setStatus("1");
					if (!role.update()) {
						throw new Exception("失败!");
					}

				}
			}
			return R.ok();
		} catch (Exception e) {
			return R.failed(e.getMessage());
		}
	}

	@Tx
	@RequestMapping(value = "/deleteById", method = RequestMethod.GET)
	public R<String> deleteById(@RequestParam(name = "id") String id) throws Exception {
		try {
			Role role = Role.dao.findById(id);
			if (role == null)
				return R.failed("数据不存在，刷新后尝试!");
			if (StrKit.equals(role.getCode(), "SuperSystem"))
				return R.failed("默认数据不可以删除!");
			role.setDelFlag("1");
			role.setStatus("1");
			if (role.update())
				return R.ok();
			return R.failed("失败！");
		} catch (Exception e) {
			return R.failed(e.getMessage());
		}
	}

	@Tx
	@RequestMapping(value = "/saveRoleUsers", method = RequestMethod.POST)
	public R<Role> saveRoleUsers(@RequestBody String params) {
		try {
			if (StrKit.isBlank(params)) {
				return R.failed("参数必填！");
			}
			JSONObject json = JSONObject.parseObject(params);
			if (json == null || !json.containsKey("roleId")) {
				return R.failed("参数必填！");
			}

			if (json == null || !json.containsKey("userIds")) {
				return R.failed("参数必填！");
			}

			if (json == null || !json.containsKey("status")) {
				return R.failed("参数必填！");
			}

			Role role = Role.dao.findById(json.getString("roleId"));
			if (role == null) {
				return R.failed("角色不存在，请刷新再试！");
			}

			String userIds = json.getString("userIds");
			String[] users = userIds.split(",");

			if (users == null || users.length <= 0) {
				return R.failed("用户信息不存在，数据未变动！");
			}
			UserRole userRole;
			for (String id : users) {
				if (!StrKit.isBlank(id)) {
					if (StrKit.equals("0", json.getString("status"))) {
						if (!UserRole.dao.deleteByIds(id, role.getId())) {
							throw new Exception("取消用户失败！");
						}
					} else {
						userRole = new UserRole();
						userRole.setRoleId(role.getId());
						userRole.setUserId(id);
						if (!userRole.save()) {
							throw new Exception("添加用户失败！");
						}
					}
				}
			}
			return R.ok();
		} catch (Exception e) {
			return R.failed(e.getMessage());
		}
	}

	@RequestMapping(value = "/getMenuIdsById", method = RequestMethod.GET)
	public R<List<String>> getMenuIdsByRoleId(@RequestParam(name = "roleId") String roleId) {
		try {
			if (StrKit.isBlank(roleId)) {
				return R.failed("参数必填");
			}
			List<String> menuIds = new LinkedList<String>();
			List<RoleMenu> roleMenus = RoleMenu.dao.find("select * from " + RoleMenu.TABLE_NAME + " where role_id=? ",
					roleId);
			for (RoleMenu rm : roleMenus) {
				menuIds.add(rm.getMenuId());
			}
			return R.ok(menuIds);
		} catch (Exception e) {
			return R.failed(e.getMessage());
		}
	}

	@Tx
	@RequestMapping(value = "/saveMenus", method = RequestMethod.POST)
	public R<String> saveRoleMenus(@RequestParam(name = "roleId") String roleId,
			@RequestParam(name = "menuIds") String menuIds,
			@RequestParam(name = "type", required = false) String type) {
		try {
			if (StrKit.isBlank(type)) {
				return Role.saveRoleMenus(roleId, menuIds);
			} else {
				return Role.saveRoleMenus(roleId, menuIds, type);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return R.failed(e.getMessage());
		}
	}

	/**
	 * 分页获取角色用户
	 * 
	 * @param keywords
	 * @param roleId
	 * @param status
	 * @param cur
	 * @param limit
	 */
	@GetMapping(value = { "/findUsers" }, produces = "application/json; charset=utf-8")
	public R<Page<User>> findUsers(
			@RequestParam(name = "keywords", required = false, defaultValue = "") String keywords,
			@RequestParam(name = "roleId", required = true, defaultValue = "") String roleId,
			@RequestParam(name = "status", required = false, defaultValue = "") String status,
			@RequestParam(name = "cur", required = true, defaultValue = "1") int cur,
			@RequestParam(name = "limit", required = false, defaultValue = "10") int limit) {

		String sqlExceptSelect = " FROM " + User.TABLE_NAME + " o  WHERE del_flag='0' ";
		if (!StrKit.isBlank(keywords)) {
			sqlExceptSelect += " AND ( O.NAME LIKE '%" + keywords + "%' OR   O.USERNAME LIKE '%" + keywords + "%' ) ";
		}
		if (StrKit.equals("0", status)) {
			sqlExceptSelect += " AND O.ID in  (select user_id from sys_user_role where role_id='" + roleId + "' ) ";
		} else {
			sqlExceptSelect += " AND O.ID not in  (select user_id from sys_user_role where role_id='" + roleId + "' ) ";
		}
		sqlExceptSelect += "  ORDER BY   O.UPDATE_TIME desc ";
		Page<User> pages = User.dao.paginate(cur, limit, "select * ", sqlExceptSelect);
		if (pages != null && pages.getList() != null && pages.getList().size() > 0) {
			List<Dept> depts;
			String deptName = "";
			for (User user : pages.getList()) {
				depts = Dept.dao.find("select name from " + Dept.TABLE_NAME
						+ " where id in (select DEPT_ID from SYS_USER_DEPT where user_id=? ) ", user.getId());
				if (depts != null && depts.size() > 0) {
					deptName = "";
					for (Dept dept : depts) {
						deptName += dept.getName() + "|";
					}
					user.setDeptName(deptName.substring(0, deptName.length() - 1));
				}
			}
		}
		return R.ok(pages);
	}

	/**
	 * 下拉框
	 * 
	 * @param keywords
	 * @return
	 */
	@RequestMapping(value = "/getOptions", method = RequestMethod.GET)
	public R<List<Role>> getOptions(@RequestParam(name = "keywords", required = false) String keywords) {
		String _sql = "select * from " + Role.TABLE_NAME + " where del_flag='0' ";
		if (!StrKit.isBlank(keywords)) {
			_sql += " and ( name like '%" + keywords + "%' or code like '%" + keywords + "%'  ) ";
		}
		_sql += " order by order_num desc ";
		return R.ok(Role.dao.find(_sql));
	}

	@RequestMapping(value = "/getRoleInfoById", method = RequestMethod.GET)
	public R<Role> getRoleInfoById(@RequestParam(name = "id") String id) throws Exception {
		try {
			if (StrKit.isBlank(id)) {
				return R.failed("参数必填！");
			}
			Role role = Role.dao.findById(id);
			if (role == null)
				return R.failed("数据不存在，刷新后尝试!");
			if (StrKit.equals(role.getCode(), "SuperSystem"))
				return R.failed("默认数据不可以修改!");
			return R.ok(role);
		} catch (Exception e) {
			return R.failed(e.getMessage());
		}
	}

}
